package io.renren.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CorsInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 允许所有来源访问
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
        // 允许特定的请求方法
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        // 允许特定的头部信息
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        // 允许携带 cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 设置缓存时间
        response.setHeader("Access-Control-Max-Age", "3600");
        return true;
    }

/*    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
    }*/
}
